/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.bff.slimserver.musicjukebox.ui.components.DNDTree;

import java.awt.Point;
import java.awt.dnd.DnDConstants;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;

/**
 *
 * @author bfindeisen
 */
public class DefaultTreeTransferHandler extends AbstractTreeTransferHandler {

    public DefaultTreeTransferHandler(DNDTree tree, int action) {
        super(tree, action, true);
    }

    @Override
    public boolean canPerformAction(DNDTreeIFace target, DefaultMutableTreeNode draggedNode, int action, Point location) {
        TreePath pathTarget = target.getTree().getPathForLocation(location.x, location.y);
        if (pathTarget == null) {
            target.getTree().setSelectionPath(null);
            return (false);
        }
        target.getTree().setSelectionPath(pathTarget);
        if (action == DnDConstants.ACTION_COPY) {
            return (true);
        } else if (action == DnDConstants.ACTION_MOVE) {
            DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) pathTarget.getLastPathComponent();
            if (draggedNode.isRoot() || parentNode == draggedNode.getParent() || draggedNode.isNodeDescendant(parentNode)) {
                return (false);
            } else {
                return (true);
            }
        } else {
            return (false);
        }
    }

    @Override
    public boolean executeDrop(DNDTreeIFace target, DefaultMutableTreeNode draggedNode, DefaultMutableTreeNode newParentNode, int action) {
        if (action == DnDConstants.ACTION_COPY) {
            DefaultMutableTreeNode newNode = target.makeDeepCopy(draggedNode);
            ((DefaultTreeModel) target.getTree().getModel()).insertNodeInto(newNode, newParentNode, newParentNode.getChildCount());
            TreePath treePath = new TreePath(newNode.getPath());
            target.getTree().scrollPathToVisible(treePath);
            target.getTree().setSelectionPath(treePath);
            return (true);
        }
        if (action == DnDConstants.ACTION_MOVE) {
            draggedNode.removeFromParent();
            ((DefaultTreeModel) target.getTree().getModel()).insertNodeInto(draggedNode, newParentNode, newParentNode.getChildCount());

            System.out.println("Moving:\t" + draggedNode.getUserObject());
            System.out.println("To:\t" + newParentNode.getUserObject());

            TreePath treePath = new TreePath(draggedNode.getPath());
            target.getTree().scrollPathToVisible(treePath);
            target.getTree().setSelectionPath(treePath);
            return (true);
        }
        return (false);
    }
}
